import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import { IEncryption } from '../types';

/**
 * 默认加密实现（AES-256-CBC）
 */
export class DefaultEncryption implements IEncryption {
    /** 加密密钥（32字节） */
    private key: Buffer;
    
    /**
     * 构造函数
     * @param key 加密密钥（32字节）
     */
    constructor(key: string) {
        // 确保密钥长度为32字节
        const keyBuffer = Buffer.from(key);
        if (keyBuffer.length < 32) {
            this.key = Buffer.concat([keyBuffer, Buffer.alloc(32 - keyBuffer.length)]);
        } else {
            this.key = keyBuffer.slice(0, 32);
        }
    }

    /**
     * 加密数据
     * @param data 待加密的数据
     */
    encrypt(data: string): string {
        const iv = randomBytes(16);
        const cipher = createCipheriv('aes-256-cbc', this.key, iv);
        let encrypted = cipher.update(data, 'utf8', 'hex');
        encrypted += cipher.final('hex');
        return `${iv.toString('hex')}:${encrypted}`;
    }

    /**
     * 解密数据
     * @param encryptedData 加密的数据
     */
    decrypt(encryptedData: string): string {
        const [ivHex, encrypted] = encryptedData.split(':');
        const iv = Buffer.from(ivHex, 'hex');
        const decipher = createDecipheriv('aes-256-cbc', this.key, iv);
        let decrypted = decipher.update(encrypted, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    }
}
